package com.strongbj.iot.devices.smarrack.request.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.google.gson.reflect.TypeToken;
import com.strongbj.core.message.MessageHandleContext;
import com.strongbj.iot.devices.smarrack.request.handle.SetLedStateHandle;
import com.strongbj.iot.devices.smarrack.request.message.MQMessage;

@Component
public class MQMessageOfSmarRackListener extends MessageListenerAdapter {
	private static Logger logger = LogManager.getLogger(MQMessageOfSmarRackListener.class.getName());
	// 通过策略模式处理不同的信息
	private MessageHandleContext<MQMessage<Object>, Object> messageHandleContent;

	public MQMessageOfSmarRackListener() {
		super();
		this.messageHandleContent = new MessageHandleContext<>();
		// 添加消息处理类
		this.messageHandleContent.addHandleClass(new SetLedStateHandle()); // 设置LED灯的状态处理类
	}

	@JmsListener(destination = "smarRackReader", concurrency = "1")
	public void onMessage(Message message, Session session) throws JMSException {
		if (message instanceof TextMessage) {
			try {
				TextMessage tm = (TextMessage) message;
				String json = tm.getText();
				MQMessage<Object> rm = JSON.parseObject(json, new TypeToken<MQMessage<Object>>() {
				}.getType());
				this.messageHandleContent.handle(null, rm);
			} catch (Exception e) {
				logger.error("",e);
			}
		} else {
			logger.info("无法解析的mq对象消息:" + message.getClass().getName());
		}
	}
}
